package com.jule.miaozhuapc.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.jule.miaozhuapc.ano.TokenUser;
import com.jule.miaozhuapc.dao.UserDao;
import com.jule.miaozhuapc.domain.WawaUser;
import com.jule.miaozhuapc.service.UserService;

/**
 *  自定 user 参数注入
 * @author Administrator
 *
 */
@Component
public class TokenUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
	
		private Logger logger = Logger.getLogger(this.getClass());


		@Autowired  
	    public UserService userService;
	 

	  	@Override
	    public boolean supportsParameter(MethodParameter parameter) {
	        // 过滤出符合条件的参数，这里指的是加了TokenUser注解的参数
	        if (parameter.hasParameterAnnotation(TokenUser.class)) {
	            return true;
	        }
	        return false;
	    }

	    @Override
	    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
	            NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
	        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

	        ServletContext sc = request.getSession().getServletContext();

			//解决Autowired为null无法注入问题
			logger.info(" userService is " + userService);
	        if (userService == null) {
				WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext()).getAutowireCapableBeanFactory().autowireBean(this);
				logger.info(" userService is " + userService);
	        }
	        String wawaToken = request.getHeader("WAWA_TOKEN");
	        logger.info("WAWA_TOKEN = " + wawaToken);
			//
			WawaUser user = new WawaUser();
			if (wawaToken != null && !"".equals(wawaToken)) {
				user = this.userService.findByToken(wawaToken);
			}else {

			}
	        return user;
	    }
  

}